package Homework;

public class SaleTicket {

	public static void main(String[] args) {
		Ticket ticket = new Ticket();
		Thread t1 = new Thread(ticket, "淘泡泡");
		Thread t2 = new Thread(ticket, "张票票");
		Thread t3 = new Thread(ticket, "黄牛党");
		
		t1.start();
		t2.start();
		t3.start();
		
		try {
			t1.join();
			t2.join();
			t3.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("票已售完！");
	}

}


class Ticket implements Runnable {
	private int count=10;//剩余的票数
	private int num;//售出的票数
	@Override
	public void run() {
		while(true) {
			synchronized (this) {
				if(count<=0) {
					break;
				}else {
					//抢票的缓冲时间500毫秒
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					count--;
					num++;
					System.out.println(Thread.currentThread().getName()+"抢到了第"+num+"张票，剩余"+count+"张票。");
					//唤醒其他所有的线程
					this.notifyAll();
					if(Thread.currentThread().getName().equals("黄牛党")) {
						//停止该线程
						Thread.currentThread().stop();
					}
					//让线程进入等待500毫秒
					try {
						this.wait(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}